package com.jt.filter;

import org.apache.http.HttpHeaders;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * Ordered  是用来定义过滤器的优先级，数字越小，优先级越高
 * */

@ConfigurationProperties("web.request")
@Component
public class BlackUrlGlobalFilter implements GlobalFilter, Ordered {

    //定义黑名单集合
    private List<String> blackUrls = new ArrayList<>();
//    public BlackUrlGlobalFilter(){
//        blackUrls.add("/nacos/provider/echo/9002");
//        blackUrls.add("/nacos/provider/echo/9003");
//    }


    public List<String> getBlackUrls() {
        return blackUrls;
    }

    public void setBlackUrls(List<String> blackUrls) {
        this.blackUrls = blackUrls;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.获取请求路径（不需要ip和端口）
        String requestPath = request.getURI().getPath();
        System.out.println(requestPath);
        //3.判断请求路径是否是黑名单url
        if (blackUrls.contains(requestPath)){
//            return null;
            //处理方案1：抛出异常
//            throw new RuntimeException("请求已被列入");
            //处理方案2：响应一个error消息
            //告诉浏览器响应的数据类型，以及以什么编码呈现数据
            response.getHeaders().add(HttpHeaders.CONTENT_TYPE,"text/html;charset=utf-8");
            //封装响应数据
            DataBuffer data = response.bufferFactory().wrap("请求已被列入".getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(data));
        }
        //4.不是黑名单，则放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
